package com.kantboot.io.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kantboot.io.TO.JoinTO;
import com.kantboot.io.entity.CesUser;
import com.kantboot.io.exception.CesUserException;
import com.kantboot.io.exception.UpdateException;
import com.kantboot.io.mapper.CesUserMapper;
import com.kantboot.io.service.CesUserService;
import com.kantboot.io.util.CesUserUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class CesUserServiceImpl extends ServiceImpl<CesUserMapper, CesUser> implements CesUserService {

    @Resource
    CesUserMapper cesUserMapper;

    @Override
    public CesUser login(
            String username,
            String password
    ) {

        CesUser cesUser = cesUserMapper.selectOne(
                new QueryWrapper<CesUser>()
                        .eq("username", username));

        if(cesUser==null){
           cesUser=cesUserMapper.selectOne(
                   new QueryWrapper<CesUser>()
                        .eq("phone_number",username));
       }

       if(cesUser==null) {
           throw CesUserException.userNullException();
       }
       if(!cesUser.getPassword().equals(CesUserUtil.toPassword(password,cesUser.getSalt()))){
           throw CesUserException.passwordFailedException();
       }

       return cesUser;
    }

    @Override
    public void join(JoinTO joinTO) {

        /* start：如果用户名、昵称、手机号码重复则抛出异常 */
        if(cesUserMapper.selectOne(
                new QueryWrapper<CesUser>().eq("nickname",joinTO.getNickname())
        )!=null){
            throw CesUserException.nicknameNotUniqueException();
        }

        if(cesUserMapper.selectOne(
                new QueryWrapper<CesUser>().eq("phone_number",joinTO.getPhoneNumber())
        )!=null){
            throw CesUserException.phoneNumberNotUniqueException();
        }
        /* end：如果用户名、昵称、手机号码重复则抛出异常 */


        String salt= CesUserUtil.createSalt();
        String password=CesUserUtil.toPassword(joinTO.getPassword(),salt);
        if(cesUserMapper.insert(
                new CesUser()
                    .setNickname(joinTO.getNickname())
                    .setPassword(password)
                    .setSalt(salt)
                    .setPhoneNumber(joinTO.getPhoneNumber())
        )!=1) {
            throw UpdateException.faildUpdateException();
        }
    }

}
